/*
 * @Description:
 * @Author: Junhuang
 * @Date: 2022-02-21 23:19:42
 * @LastEditTime: 2022-05-24 15:32:05
 * @LastEditors: Junhuang
 * @Reference:
 */
'use strict';

const Controller = require('egg').Controller;

class CommentController extends Controller {
  async save() {
    const { ctx, app } = this;
    const user_id = ctx.authUser.id;

    ctx.validate({
      content: { type: 'string', required: true, desc: '评论内容' },
      video_id: { type: 'int', required: true, desc: '作品id' },
      reply_id: { type: 'int', required: true, desc: '回复评论id' },
    });

    const { content, video_id, reply_id } = ctx.request.body;

    const user = await app.model.User.findByPk(user_id);
    if (!user) {
      return ctx.apiFail('回复用户id参数错误');
    }

    const video = await app.model.Video.findByPk(video_id);
    if (!video) {
      return ctx.apiFail('视频不存在');
    }

    // 如果是回复评论
    if (reply_id > 0) {
      const rcomment = await app.model.Comment.findByPk(reply_id);
      if (!rcomment) {
        return ctx.apiFail('回复评论id参数错误');
      }
    }

    const res = await app.model.Comment.create({
      content,
      video_id,
      reply_id,
      user_id,
    });

    ctx.apiSuccesss(res);
  }

  // 获取某作品的评论列表,登录情况下
  // 路由：/video_comment_auth/:video_id (此处的id是作品的id)
  async comment_auth() {
    console.log('comment_auth');
    await this.comment();
  }

  // 获取某作品的评论列表
  // 路由：/video_comment/:video_id (此处的id是作品的id)
  async comment() {
    const { ctx, app } = this;
    const currentUser = ctx.authUser;
    ctx.validate({
      video_id: { type: 'int', required: true, desc: '作品id' },
    });

    const video_id = ctx.params.video_id;
    const Op = app.Sequelize.Op;
    let where = {};
    let comment_where = {};
    if (currentUser) {
      where = {
        [Op.or]: [
          {
            status: 1,
          }, {
            user_id: currentUser.id,
          },
        ],
      };
      comment_where = {
        [Op.or]: [
          {
            status: 1,
          }, {
            user_id: currentUser.id,
          },
        ],
      };
    } else {
      where.status = 1;
      comment_where.status = 1;
    }
    where.video_id = video_id;
    where.reply_id = 0;
    console.log('where,comment_where', where, comment_where);
    const res = await app.model.Comment.findAll({
      where,
      include: [{
        model: app.model.User,
        as: 'send_user',
        attributes: [ 'id', 'username', 'nickname', 'avatar' ],
      }, {
        model: app.model.Comment,
        where: comment_where,
        required: false,
        // 【特别注意】此处在关联commnets中，继续进行关联user表
        include: [{
          model: app.model.User,
          as: 'send_user',
          attributes: [ 'id', 'username', 'nickname', 'avatar' ],
        }],
      }],
      // 【特别注意】注意此处对关联加载项的排序的写法
      order: [[ 'id', 'DESC' ], [{ model: app.model.Comment }, 'id', 'ASC' ]],
    });
    return ctx.apiSuccesss(res);
  }

  // 获取评论列表分页-后台
  async list() {
    const { ctx, app } = this;
    const where = {};
    const video_where = {}; // 作品查询条件
    const sender_where = {}; // 评论人查询条件
    const user_where = {}; // 作者查询条件
    const Op = app.Sequelize.Op;

    // 组织查询条件
    // 评论id用全等
    if (ctx.query.id && ctx.query.id.length > 0) {
      where.id = ctx.query.id;
    }

    // stauts全等
    if (ctx.query.status) {
      where.status = parseInt(ctx.query.status);
    }

    // content用like
    if (ctx.query.content && ctx.query.content.length > 0) {
      where.content = {
        [Op.like]: '%' + ctx.query.content + '%',
      };
    }

    // sender的nickname用like
    if (ctx.query.snickname && ctx.query.snickname.length > 0) {
      sender_where.nickname = {
        [Op.like]: '%' + ctx.query.snickname + '%',
      };
    }

    // type: 1:评论，2:回复评论
    if (ctx.query.type) {
      if (ctx.query.type === 2) {
        where.reply_id > 0;
      } else {
        where.reply_id = 0;
      }
    }

    // 时间

    // 作品名称：vtitle用like
    if (ctx.query.vtitle && ctx.query.vtitle.length > 0) {
      video_where.title = {
        [Op.like]: '%' + ctx.query.vtitle + '%',
      };
    }

    // 作品用户：vtitle用like
    if (ctx.query.vnickname && ctx.query.vnickname.length > 0) {
      user_where.nickname = {
        [Op.like]: '%' + ctx.query.vnickname + '%',
      };
    }

    const sequelize = app.model;
    const options = {
      include: [{
        model: app.model.Video,
        attributes: [ 'id', 'title', 'cover' ],
        include: [{
          model: app.model.User,
          attributes: [ 'id', 'username', 'nickname', 'avatar' ],
          where: user_where,
        }],
        where: video_where,
      }, {
        model: app.model.User,
        as: 'send_user',
        where: sender_where,
        attributes: [ 'id', 'username', 'nickname', 'avatar' ],
      }, {
        model: app.model.Comment,
        as: 'rcomment',
        attributes: [ 'id', 'content' ],
      }],
      order: [[ 'video', 'id' ], sequelize.literal('IFNULL(`rcomment`.`id`,`comment`.`id`) ASC'), [ 'id', 'ASC' ]],
    };

    const res = await ctx.pageAndCount(app.model.Comment, where, options);
    const items = [];
    res.rows.forEach(el => {
      const item = JSON.parse(JSON.stringify(el));
      if (el.video) {
        item.video_title = el.video.title;
        item.video_cover = el.video.cover;
        if (el.video.user) {
          item.user_nickname = el.video.user.nickname;
          item.user_username = el.video.user.username;
          item.user_id = el.video.user.id;
          item.user_avatar = el.video.user.avatar;
        }
        delete item.video;
      }
      if (el.send_user) {
        item.sender_nickname = el.send_user.nickname;
        item.sender_username = el.send_user.username;
        item.sender_id = el.send_user.id;
        item.sender_avatar = el.send_user.avatar;
      }
      if (el.rcomment) {
        item.reply_comment_content = '评论：' + el.rcomment.content;
      } else {
        item.reply_comment_content = '作品：' + item.video_title;
      }
      items.push(item);
    });
    ctx.apiSuccesss({
      total: res.count,
      items,
    });
  }

  // 评论
  async changeStatus() {
    const { ctx, app } = this;
    let { status } = ctx.request.body;
    status = parseInt(status);
    ctx.validate({
      id: {
        required: true,
        type: 'int',
        desc: 'id',
      },
      status: {
        required: true,
        type: 'int',
        desc: 'status',
      },
    });

    const comment = await app.model.Comment.findOne({
      where: {
        id: ctx.params.id,
      },
    });

    if (!comment) {
      return ctx.throw(404, '该评论不存在');
    }

    if (comment.status === status) {
      return ctx.throw('该评论状态与要变化的状态一致，不用变化！');
    }

    comment.status = status;
    comment.save();

    const res = JSON.parse(JSON.stringify(comment));
    return ctx.apiSuccesss(res);
  }
}

module.exports = CommentController;
